package com.snail.billing.data;

import java.io.StringReader;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;

import com.alipay.android.app.pay.PayTask;
import com.alipay.android.app.pay.PayTask.OnPayListener;
import com.android.os.IPageManager;
import com.snail.billing.os.DialogPageActivity;
import com.snail.billing.page.PaymentOkPage;
import com.snail.billing.page.PaymentWebViewPage;
import com.snail.billing.wxapi.WXPayEntryActivity;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.unionpay.upomp.lthj.util.PluginHelper;

public class PaymentLogic {

	public static final byte STATE_IMPREST = 0;
	public static final byte STATE_PAYMENT = 1;
	public static final byte STATE_IMPREST2 = 2;

	private IPageManager manager;
	private int state;
	private Handler handler;

	private WxPayResultReceiver wxPayResultReceiver;

	public PaymentLogic(IPageManager manager, int state) {
		this.manager = manager;
		this.state = state;
		handler = new Handler(Looper.getMainLooper());
	}

	private Context getContext() {
		return getPageManager();
	}

	private DialogPageActivity getPageManager() {
		return (DialogPageActivity) manager;
	}

	private void forward() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				Bundle args = new Bundle();
				args.putInt("state", state);
				getPageManager().forward(PaymentOkPage.class, args);
			}
		});
	}

	private void backward(final String message) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
				if (state == STATE_IMPREST || state == STATE_IMPREST2) {
					getPageManager().backward();
				} else if (state == STATE_PAYMENT) {
					getPageManager().finish();
				}
			}
		});
	}

	/** 支付宝客户端 */
	public void alipayApp(String source) {
		PayTask payTask = new PayTask(getPageManager(), new OnPayListener() {

			@Override
			public void onPaySuccess(Context context, String resultStatus, String memo, String result) {
				forward();
			}

			@Override
			public void onPayFailed(Context context, String resultStatus, String memo, String result) {
				backward(memo);
			}
		});
		payTask.pay(source);
	}

	/** 银联客户端 */
	public void upompApp(byte[] to_upomp) {
		Bundle bundle = new Bundle();
		bundle.putByteArray("xml", to_upomp);
		bundle.putString("action_cmd", "cmd_pay_plugin");
		// 更换参数调起测试与生产插件,value为true是测试插件 ，为false是生产插件
		// bundle.putBoolean("test", true);
		bundle.putBoolean("test", false);
		PluginHelper.LaunchPlugin(getContext(), upompHandler, bundle);
	}

	private Handler upompHandler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(Message msg) {
			try {
				if (msg.obj == null) {
					return;
				}
				byte[] xmlBytes = (byte[]) msg.obj;
				String xml = new String(xmlBytes, "utf-8");
				SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
				UpompXmlHander xmlHandler = new UpompXmlHander();
				saxParser.parse(new InputSource(new StringReader(xml)), xmlHandler);
				if ("0000".equals(xmlHandler.respCode)) {
					forward();
				} else {
					backward(xmlHandler.respDesc);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private class UpompXmlHander extends DefaultHandler {

		private String localName;
		public String respCode;
		public String respDesc;

		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			this.localName = localName;
		}

		@Override
		public void characters(char[] ch, int start, int length) throws SAXException {
			String value = String.valueOf(ch, start, length);
			if ("respCode".equals(localName)) {
				respCode = value;
			} else if ("respDesc".equals(localName)) {
				respDesc = value;
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException {
			this.localName = null;
		}

	}

	/** 支付宝Web */
	public void alipayWeb() {
		Bundle args = new Bundle();
		args.putInt("state", state);
		getPageManager().forward(PaymentWebViewPage.class, args);
	}

	/** 财付通Web */
	public void tenpayWeb() {
		Bundle args = new Bundle();
		args.putInt("state", state);
		getPageManager().forward(PaymentWebViewPage.class, args);
	}

	/** 微信客户端 */
	public void wxpayApp(PayReq payReq) {
		try {
			wxPayResultReceiver = new WxPayResultReceiver();
			IntentFilter intentFilter = new IntentFilter(WXPayEntryActivity.WXPAY_RESULT_RECEIVER);
			getContext().registerReceiver(wxPayResultReceiver, intentFilter);
		} catch (Exception e) {
			e.printStackTrace();
		}
		IWXAPI api = WXAPIFactory.createWXAPI(getContext(), payReq.appId);
		api.registerApp(payReq.appId);
		if (!api.isWXAppInstalled()) {
			Toast.makeText(getContext(), "您尚未安装微信，请安装后再试", Toast.LENGTH_SHORT).show();
		} else if (!api.isWXAppSupportAPI()) {
			Toast.makeText(getContext(), "您的微信版本过低，请升级微信后再试", Toast.LENGTH_SHORT).show();
		} else {
			api.sendReq(payReq);
		}
	}

	private class WxPayResultReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			int errCode = intent.getIntExtra("wxcode", -2);
			if (errCode == 0) {
				forward();
			} else {
				backward("支付失败");
			}
			if (wxPayResultReceiver != null) {
				getContext().unregisterReceiver(wxPayResultReceiver);
			}
		}

	}

}
